package com.hfzy.ihk.web.freeswitchCall.biz;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.facade.calldata.service.EsOptRmiService;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 将数据推送到Es 业务类
 */
@Component
public class PushDataToEsBiz {

    Logger logger = LoggerFactory.getLogger(PushDataToEsBiz.class);


    @Autowired
    RedisTemplate redisTemplate;
    //retries 表示失败重试次数 默认两次
    /*@Reference(version = "1.0.0",check = false,retries=0,timeout = 5000)
    EsOptRmiService esOptRmiService;*/
    @Value("${pushdata.callhistory.data-url}")
    private String pushDataUrl;

    /**
     *
     * @param sessionId 对应的sessionId
     * @param jsonData
     * @param deleteKey  需要删除的deleteKey 推送成功就删除,不需要就传null
     */
    public void pushCallHistoryToEs(String sessionId,String jsonData,String deleteKey,boolean isJob){
        try {
            logger.info("----------------开始推送到ES,sessionId:"+sessionId);
             //String rs =esOptRmiService.createOrUpdateCloudCallHistoryBySessionId(jsonData);
             String rs = pushDataToEs(jsonData);
             logger.info("---->push es rs:{}",rs);
             if(rs.equals("1")) { //成功

                 //假如是重推任务,删除redis的sessionId
                 if(isJob){

                     redisTemplate.opsForSet().remove(RedisKey.PUSH_TO_ES_FAILED_HISTORY,sessionId);

                     logger.info("------------------通话记录重推到es成功,sessionId为"+sessionId);
                  }else{

                     logger.info("-------------------推送到ES成功sesionId:{}",sessionId);
                 }

             }else{ //失败
                 try {
                     logger.info("-------------------推送到ES失败!!sesionId:{}",sessionId);
                     redisTemplate.opsForSet().add(RedisKey.PUSH_TO_ES_FAILED_HISTORY, sessionId);
                 }catch (Exception e1){
                     logger.error("将推送ES 失败数据放入redis 失败！sessionId：{}",sessionId,e1);
                 }
             }
        }catch (Exception  e){
            try {
                logger.error("-->推送数据到es失败，放入redis",e);
                redisTemplate.opsForSet().add(RedisKey.PUSH_TO_ES_FAILED_HISTORY, sessionId);
            }catch (Exception e1){
                logger.error("将推送ES 失败数据放入redis 失败！sessionId：{}",sessionId,e1);
            }
        }

    }


    /**
     * 将录音文件推送到ES
     * @param sessionId
     * @param url
     * @param jsonData
     */
    public void pushRecordFileToEs(String sessionId,String url,String jsonData){
        try {

            String rs = pushDataToEs(jsonData);
            logger.info("----->push record es:{}",rs);
            if(rs.equals("0")){

                logger.error("---->推送录音url到es失败,不删除redis的数据,sessionId:"+sessionId);

            }else{

                logger.info("推送录音url到es成功,url:{},sessionId:{}",url,sessionId);

                //删除redis的Key
                removePushUrlFormRedis(sessionId,url);

            }

        }catch (Exception  e){
            logger.error("-->推送录音url数据到es失败，不删除redis的数据,sessionId:"+sessionId,e);
        }

    }
    /*public void pushRecordFileToEs(String sessionId,String url,String jsonData,boolean isJob){
        try {

            String rs = pushDataToEs(jsonData);
            logger.info("----->push record es:{}",rs);
            if(rs.equals("0")){

                logger.error("-->推送录音url到es失败");
                if (!isJob){  //假如是重推任务,不需要再存入redis
                    try {
                        redisTemplate.opsForSet().add(RedisKey.PUSH_RECORD_URL_TO_ES_FAILED, sessionId+"::"+url);
                        logger.info("将推送ES 录音url 失败数据放入redis 成功！sessionId：{}",sessionId);
                    }catch (Exception e1){
                        logger.error("将推送ES 录音url 失败数据放入redis 失败！sessionId：{}",sessionId,e1);

                    }
                }
            }else{
                if (isJob){ //假如是重推任务,成功后删除redis数据,免得堆积
                        redisTemplate.opsForSet().remove(RedisKey.PUSH_RECORD_URL_TO_ES_FAILED, sessionId+"::"+url);
                }

                logger.info("推送录音url到es成功,url:{},sessionId:{}",url,sessionId);
            }
        }catch (Exception  e){
            logger.error("-->推送数据到es失败，放入redis,sessionId:"+sessionId,e);
            try {
                redisTemplate.opsForSet().add(RedisKey.PUSH_RECORD_URL_TO_ES_FAILED, sessionId+"::"+url);
            }catch (Exception e1){
                logger.error("将推送ES 录音url 失败数据放入redis 失败！sessionId：{}",sessionId,e1);

            }
        }

    }*/

    /**
     * 通过http请求推送数据到es
     */
    public String pushDataToEs(String jsonStr){

        long startTime = System.currentTimeMillis();

        Map<String,String> paramMap=new HashMap<>();

        paramMap.put("jsonStr",jsonStr);

        String result = HttpClientUtils.postMethod(pushDataUrl, paramMap, null);

        logger.info("freeswitchlog:推送freeswitch呼叫记录到es,耗时{}",System.currentTimeMillis()-startTime);

        return "true".equals(result)?"1":"0";
    };

    /**
     * 获取延迟时间的date
     * @return
     */
    public Date getDelayTime(int delayTime){

        Calendar instance = Calendar.getInstance();

        instance.add(Calendar.SECOND,delayTime);

        return  instance.getTime();
    }

    /**
     * 推送录音url到es成功后,删除Redis中的Key
     */
    public void  removePushUrlFormRedis(String url,String sessionId){

        try {

            redisTemplate.opsForSet().remove(RedisKey.PUSH_URL_TO_ES_SET,url+"::"+sessionId);

            logger.info("将储存在redis的数据删除成功(推送到es的录音url),sessionId:"+sessionId);

        }catch (Exception e){

            logger.info("将储存在redis的数据删除失败(推送到es的录音url),sessionId:"+sessionId);
        }

    }

    /**
     * 将需要推送录音url到es的数据保存到
     * @param
     */
    public void setSessionIdToReids(String sessionId,String recordFileUrl) {

            try {

                redisTemplate.opsForSet().add(RedisKey.PUSH_URL_TO_ES_SET,sessionId+"::"+recordFileUrl);

                logger.info(">>>>>>>>将需要推送录音url到Es的数据保存到redis成功！,sessionId:"+sessionId);

            }catch ( Exception e){
                logger.error(">>>>>>>>将需要推送录音url到Es的数据保存到redis失败！,sessionId:"+sessionId,e);
            }

    }
}
